<template>
  <el-input v-model="message" v-bind="options" />
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { computed } from 'vue';
import { getRegion } from "@/utils/system";
import visual from "@/visual/js/visual";

const props = defineProps({
  node: Object,
  compStyle: Object,
  compData: Object
});
const currNode = ref(props.node);
const currValue = ref('');
const treeData = ref([]);
const message = ref('');

const options = computed(() => {
  const compStyle = props.compStyle || {};
  return {
    placeholder: compStyle['placeholder'] || '--请选择--'
  };
});

const calcValue = async() => {
  if (treeData.value && treeData.value.length > 0) {
    const ids = (currValue.value || '').split(',');
    const list = findData(treeData.value, ids);
    if (list && list.length > 0) {
      for (let i = 0; i < list.length; i++) {
        message.value = list[i].text;
      }
    } else {
      message.value = '';
    }
  } else {
    message.value = '';
  }
};

const findData = (list, ids) => {
  let results = [];
  if (list === undefined || list == null || ids === undefined || ids == null) {
    return results;
  }

  for (let i = 0; i < list.length; i++) {
    const id = list[i].id + '';
    if (id !== '0' && ids.indexOf(id) >= 0) {
      results.push(list[i]);
    }

    if (list[i].children !== undefined && list[i].children != null) {
      results = results.concat(findData(list[i].children, ids));
    }
  }

  return results;
};

const loadTree = async () => {
  treeData.value = await getRegion();
  await calcValue();
};

const loadValue = async() => {
  const dataList = (await visual.loadData(props.compData, {}, {}, currNode.value)).data || [];
  currNode.value.compData.dataList = JSON.stringify(dataList);
  currValue.value = dataList.length > 0 && dataList[0]['内容'] || '';
  await calcValue();
};

watch(() => props.compStyle, () => {
  loadValue();
}, {deep: true});

watch(() => props.compData?.refresh, () => {
  loadValue();
});

onMounted(() => {
  loadTree();
  loadValue();
});
</script>